/**
 * Copyright (c) 2020 kedacom
 * OpenATC is licensed under Mulan PSL v2.
 * You can use this software according to the terms and conditions of the Mulan PSL v2.
 * You may obtain a copy of Mulan PSL v2 at:
 * http://license.coscl.org.cn/MulanPSL2
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PSL v2 for more details.
 **/
<template>
  <div class="historical-params-dialog">
    <Messagebox :visible="readDiologVisible" :text="`${$t('edge.record.readinfo')}`" @cancle="cancleRead" @ok="handleRead"/>
    <el-dialog
        :title="$t('edge.main.historicalParameters')"
        :visible.sync="visible"
        width="80%"
        :modal-append-to-body="false"
        :close-on-click-modal="false"
        @close='handleClose'>
        <div class="onePageTable">
          <div class="commonTablePanel edge-operationrecord">
            <el-dialog width="35%" :visible.sync="viewVisible" append-to-body>
              <div class="json-view-modal">
                <json-view :deep="5" :theme="jsonViewTheme" :data="exportData" />
              </div>
            </el-dialog>
            <div class="common-table-header" style="display:inline-block;width:100%;">
              <div class="filter-container" style="float:right;margin-right:20px;">
                <div class="filters">
                  <span class="header-span">{{$t('edge.record.originadress') }}：</span>
                  <el-input
                      @keyup.enter.native="onConditionChange()"
                      v-model="source"
                      style="width:120px;">
                    <el-button
                        slot="append"
                        @click="onConditionChange"
                        icon="el-icon-search"
                      ></el-button>
                  </el-input>
                </div>

                <div class="filters">
                  <span class="header-span">{{$t('edge.record.reponsestatus') }}：</span>
                  <SelectReponseStatus ref="selectReponseStatus"
                                      style="width:120px;"
                                      @onChange="onConditionChange"></SelectReponseStatus>
                </div>

                <div class="filters">
                  <span class="header-span">{{$t('edge.login.username') }}：</span>
                  <el-input
                      v-model="operator"
                      style="width:120px;"
                  >
                  <el-button
                  slot="append"
                  @click="onConditionChange"
                  icon="el-icon-search"
                ></el-button>
                </el-input>
                </div>
                <div class="filters timepicker">
                  <span class="header-span">{{$t('edge.record.opertime') }}：</span>
                  <template >
                    <el-date-picker
                      style="width: 350px;"
                      v-model="timeValue"
                      popper-class="common-date-popper"
                      type="datetimerange"
                      range-separator="-"
                      :start-placeholder="$t('edge.record.starttime')"
                      :end-placeholder="$t('edge.record.endtime')"
                      @change="onConditionChange">
                    </el-date-picker>
                  </template>
                </div>
              </div>
            </div>
            <div class="atc-table" id="footerBtn">
              <el-table
                :data="tableData"
                :max-height="tableHeight"
                style="height: 100%;font-size: 14px;"
                v-loading.body="listLoading">
                <el-table-column
                  label='#'
                  type="index"
                  align="center">
                </el-table-column>
                <el-table-column
                  prop="operator"
                  :label="$t('edge.record.user')"
                  align="center">
                </el-table-column>
                <el-table-column
                  prop="source"
                  :label="$t('edge.record.originadress')"
                  align="center">
                </el-table-column>
                <el-table-column
                  prop="status"
                  :label="$t('edge.record.reponsestatus')"
                  align="center"
                  :formatter="formatterStatus">
                </el-table-column>
                <el-table-column
                  width="400px"
                  prop="responseCode"
                  :formatter="formatterResponseCode"
                  :label="$t('edge.record.errorReason')"
                  align="center">
                </el-table-column>
                <el-table-column
                  prop="opertime"
                  :label="$t('edge.record.opertime')"
                  sortable
                  align="center">
                </el-table-column>
                <el-table-column :label="$t('edge.record.opera')" align="center">
                <template slot-scope="scope">
                    <el-button type="text" @click="derive(scope.$index)">{{$t('edge.record.view')}}</el-button>
                    <el-button type="text" @click="read(scope.$index)">{{$t('edge.record.read')}}</el-button>
                </template>
                </el-table-column>
              </el-table>
             <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="listQuery.pageNum" :page-size="listQuery.pageRow" :total="totalCount" :page-sizes="[10, 20, 50, 100]" layout="total, sizes, prev, pager, next, jumper" style='margin:0px;'>
            </el-pagination>
          </div>
          </div>
        </div>
    </el-dialog>
  </div>
</template>

<script>
import moment from 'moment'
import jsonView from 'vue-json-views'
import { getHisParamsList, getHisParamsRange, exportHisParams } from '../../api/table'
import { getTheme } from '../../utils/auth.js'
import { getErrorMesZh, getErrorMesEn } from '../../utils/errorcode'
import { getMessageByCode } from '../../utils/responseMessage'
import SelectReponseStatus from '../../components/SelectReponseStatus'
import Messagebox from '@/components/MessageBox/index'
import { getIframdevid } from '@/utils/auth'

export default {
  name: 'historicalParamsDialog',
  props: {
    historicalVisible: {
      type: Boolean
    }
  },
  components: {jsonView, SelectReponseStatus, Messagebox},
  watch: {
  },
  data () {
    return {
      visible: this.historicalVisible,
      source: '',
      infotype: '',
      status: '',
      agentid: '',
      menuOperateRecord: '',
      operator: '',
      exportData: {},
      timeValue: [new Date().getTime() - 3600 * 1000 * 24, new Date()],
      tableHeight: '700',
      schfilter: '',
      listLoading: false,
      tableData: [],
      // exportData: [],
      infotypeMode: new Map([['control/pattern', '控制消息'], ['control/interrupt', '方案控制消息'], ['control/preempt', '优先控制'], ['system/channelcheck', '通道检测'], ['control/remote', '远程控制'], ['system/centerip', '中心ip地址'], ['system/ip1', '设备ip地址1'], ['system/ip2', '设备ip地址2'], ['system/serialport', '串口信息'], ['system/time', '系统时间'], ['system/remote', '远程调试'], ['system/update', '系统更新'], ['system/paramversion', '参数版本'], ['system/optstatparam', '优化统计参数'], ['system/faultclear', '故障消除'], ['system/udiskupdate', '更新U盘数据'], ['system/volumelog', '交通流量历史数据'], ['feature/channel', '通道'], ['feature/phase', '相位'], ['feature/overlap', '跟随相位'], ['feature/pattern', '方案'], ['feature/plan', '计划'], ['feature/date', '日期'], ['feature/peddetecter', '行人检测器'], ['feature/devinfo', '设备信息'], ['feature/manualpanel', '手动面板配置'], ['feature/channellock', '通道灯色锁定参数配置'], ['feature/all', '整体参数']]),
      // infotypeModeEn: new Map([['control/pattern', '控制消息'], ['control/interrupt', '方案控制消息'], ['control/preempt', '优先控制'], ['system/channelcheck', '通道检测'], ['control/remote', '远程控制'], ['system/centerip', '中心ip地址'], ['system/ip1', '设备ip地址1'], ['system/ip2', '设备ip地址2'], ['system/serialport', '串口信息'], ['system/time', '系统时间'], ['system/remote', '远程调试'], ['system/update', '系统更新'], ['system/paramversion', '参数版本'], ['system/optstatparam', '优化统计参数'], ['system/faultclear', '故障消除'], ['system/udiskupdate', '更新U盘数据'], ['system/volumelog', '交通流量历史数据'], ['feature/channel', '通道'], ['feature/phase', '相位'], ['feature/overlap', '跟随相位'], ['feature/pattern', '方案'], ['feature/plan', '计划'], ['feature/date', '日期'], ['feature/peddetecter', '行人检测器'], ['feature/devinfo', '设备信息'], ['feature/manualpanel', '手动面板配置'], ['feature/channellock', '通道灯色锁定参数配置'], ['feature/all', '整体参数']]),
      listQuery: {
        pageNum: 1, // 页码
        pageRow: 50 // 每页条数
      },
      totalCount: 0, // 分页组件--数据总条数
      viewVisible: false,
      jsonViewTheme: getTheme() === 'light' ? '' : 'vs-code',
      readDiologVisible: false
    }
  },
  methods: {
    handleClose () {
      this.$emit('closeHistoricalParams')
    },
    onConditionChange (val) {
      this.listQuery = {
        pageNum: 1, // 页码
        pageRow: 50 // 每页条数
      }
      this.getList()
    },
    onSearchClick () {
      this.getList()
    },
    getReqData () {
      let reqData = {}
      let from = moment(this.timeValue[0]).format('YYYY-MM-DD HH:mm:ss')
      let to = moment(this.timeValue[1]).format('YYYY-MM-DD HH:mm:ss')
      let status = this.$refs.selectReponseStatus.value
      reqData = {
        agentId: getIframdevid(),
        source: this.source,
        response_code: status,
        operator: this.operator,
        beginTime: from,
        endTime: to,
        pageNum: this.listQuery.pageNum,
        pageRow: this.listQuery.pageRow
      }
      return reqData
    },
    getList () {
      let reqData = this.getReqData()
      this.listLoading = true
      getHisParamsRange(reqData).then(data => {
        if (data.data.success !== true) {
          this.listLoading = false
          if (data.data.code === '20004') {
            this.$message.error('无参数记录!')
            return
          }
          this.$message.error(getMessageByCode(data.data.code, this.$i18n.locale))
          return
        }
        this.listLoading = false
        this.tableData = this.handleData(data.data.data.content)
        this.totalCount = data.data.data.total
      })
    },
    formatterStatus (row, column) {
      let res = ''
      if (row.responseCode === '0') {
        res = this.$t('edge.record.success')
      } else if (row.responseCode === '4001') {
        res = this.$t('edge.record.errorrequest')
      } else if (row.responseCode === '4002') {
        res = this.$t('edge.record.errorranswer')
      } else if (row.responseCode === '4003') {
        res = this.$t('edge.record.devicedown')
      } else if (row.responseCode === '4004') {
        res = this.$t('edge.record.duplicateid')
      } else if (row.responseCode === '4005') {
        res = this.$t('edge.record.signalempty')
      } else if (row.responseCode === '4006') {
        res = this.$t('edge.record.signaltypenull')
      } else if (row.responseCode === '4007') {
        res = this.$t('openatccomponents.message.4007')
      } else if (row.responseCode === '4008') {
        res = this.$t('openatccomponents.message.4008')
      } else if (row.responseCode === '4009') {
        res = this.$t('openatccomponents.message.4009')
      } else if (row.responseCode === '4010') {
        res = this.$t('openatccomponents.message.4010')
      }
      return res
    },
    formatterSubInfoType (row, column) {
      let res = row.subInfoType
      if (row.infotype === 'control/pattern') {
        let selectControl = this.$refs.selectControl
        if (selectControl) {
          res = selectControl.getNameById(res)
        }
      } else {
        res = ''
      }
      return res
    },
    formatterResponseCode (row, column) {
      if (row.responseCode === '4002' && row.innerErrorCode === '4209') {
        let success = row.responsebody.success
        if (success !== 0) {
          let msg = this.$t('edge.record.answererror')
          let errormsg = this.$t('openatccomponents.overview.putTscControlError' + success)
          // this.$message.error(this.$t(errormsg))
          return msg + ':' + errormsg
          //   return
        }
      }
      if (row.responseCode === '4002' && row.innerErrorCode === '4207') {
        // 信号机参数校验
        let codeList = row.responsebody.errorCode
        // if (codeList.length === 0) {
        //   this.$message.error(this.$t('edge.errorTip.saveParamFailed'))
        //   return
        // }
        let mes = this.$t('edge.record.parametererror')
        let errorMes = this.$t('edge.common.downloaderror')
        for (let code of codeList) {
          if (this.$i18n.locale === 'en') {
            errorMes = getErrorMesEn(errorMes, code)
          } else {
            errorMes = getErrorMesZh(errorMes, code)
          }
        }
        return mes + ':' + errorMes
      }
    },
    leadingOut (data) {
      // 定义文件内容，类型必须为Blob 否则createObjectURL会报错
      // const tscParam = this.globalParamModel.getGlobalParams()
      let content = new Blob([JSON.stringify(data)])
      // 生成url对象
      let urlObject = window.URL || window.webkitURL || window
      let url = urlObject.createObjectURL(content)
      // 生成<a></a>DOM元素
      let el = document.createElement('a')
      // 链接赋值
      el.href = url
      el.download = 'export.txt'
      // 必须点击否则不会下载
      el.click()
      // 移除链接释放资源
      urlObject.revokeObjectURL(url)
    },
    getAllRecord () {
      this.listLoading = true
      getHisParamsList(this.listQuery.pageNum, this.listQuery.pageRow).then(data => {
        if (data.data.success !== true) {
          this.listLoading = false
          if (data.data.code === '20004') {
            this.$message.error('无参数记录!')
            return
          }
          this.$message.error(getMessageByCode(data.data.code, this.$i18n.locale))
          return
        }
        this.listLoading = false
        this.tableData = this.handleData(data.data.data.content)
        this.totalCount = data.data.data.total
      })
    },
    derive (index) {
      let id = this.tableData[index].id
      exportHisParams(id).then(data => {
        if (data.data.success !== true) {
          this.$message.error(getMessageByCode(data.data.code, this.$i18n.locale))
          return
        }
        this.exportData = data.data.data
        // this.leadingOut(exportData)
        // this.$alert(`<pre>${JSON.stringify(exportData, null, 4)}</pre>`, '', {
        //   customClass: 'recordJsonModal',
        //   showConfirmButton: false,
        //   dangerouslyUseHTMLString: true
        // })
        this.viewVisible = true
      })
    },
    read (index) {
      this.readDiologVisible = true
      this.readIndex = index
    },
    cancleRead () {
      this.readDiologVisible = false
    },
    handleRead () {
      this.loadHistoryParams()
      this.readDiologVisible = false
    },
    loadHistoryParams () {
      let id = this.tableData[this.readIndex].id
      exportHisParams(id).then(data => {
        if (data.data.success !== true) {
          this.$message.error(getMessageByCode(data.data.code, this.$i18n.locale))
          return
        }
        this.globalParamModel.reset()
        setTimeout(() => {
          console.log(data.data.data)
        let result = JSON.parse(JSON.stringify(data.data.data.requestbody))
        this.globalParamModel.setGlobalParams(result)
        this.$message.success(this.$t('edge.errorTip.readSchemeSucc'))
      }, 50)
      })
    },
    handleData (data) {
      let that = this
      for (let obj of data) {
        Object.keys(obj).forEach(function (key) {
          if (key === 'infotype') {
            if (that.$i18n.locale === 'zh') {
              // obj[key] = that.infotypeMode.get(obj[key])
              obj['infotypeName'] = that.infotypeMode.get(obj[key])
            }
          }
        })
      }
      return data
    },
    handleSizeChange (val) {
      // 改变每页数量
      this.listQuery.pageRow = val
      this.getList()
    },
    handleCurrentChange (val) {
      // 改变页码
      this.listQuery.pageNum = val
      this.getList()
    }
  },
  mounted () {
    var _this = this
    this.globalParamModel = this.$store.getters.globalParamModel
    this.$nextTick(() => {
      setTimeout(() => {
        const offsetTop = document.querySelector('#footerBtn').offsetTop
        _this.tableHeight = window.innerHeight - offsetTop - 250
        _this.getList()
      })
    })
  }
}
</script>
